<?php

namespace App\Service\Third\Xiaoke;

use App\Models\Third\Xiaoke\ClueChangeOwnerRecordModel;
use App\Models\Third\Xiaoke\ClueModel;
use App\Models\Third\Xiaoke\ClueToCustomerModel;
use App\Models\Third\Xiaoke\CustomerStageDataModel;
use App\Models\Third\Xiaoke\UserModel;
use App\Remote\XiaoKe\CustomerRemote;
use App\Service\BaseService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Validation\ValidationException;

class XiaokeService extends BaseService
{
    /**
     * 销氪回调
     *
     * @param object $params
     */
    public static function notify(object $params)
    {
        $functionName = "{$params->kfBusinessType}Notify";
        self::$functionName($params);
    }

    /**
     * 线索回调
     *
     * @param object $params
     */
    public static function clueNotify(object $params)
    {
        $msgBodyArr  = json_decode($params->msg_body, true);
        $locationArr = jsonToArr($msgBodyArr["clue"][0]["s_location"][4] ?? "", []);

        ClueModel::query()->insert([
            "businessId"        => $params->business_id,
            "event"             => $params->event,
            "publicAccountId"   => $params->public_account_id,
            "notifyId"          => $params->id,
            "topic"             => $params->topic,
            "originalMsgBody"   => $params->msg_body,
            "buildTime"         => $msgBodyArr["buildTime"],
            "clueId"            => $msgBodyArr["clue"][0]["id"], // 线索id
            "interactiveMode"   => $msgBodyArr["clue"][0]["c_jiaohufangshi1"] ?? "", // 交互方式
            "source"            => $msgBodyArr["clue"][0]["c_xiansuolaiyuan24"] ?? "", // 线索来源
            "followStatus"      => $msgBodyArr["clue"][0]["s_follow_status"],//跟进状态
            "mobilePhone"       => $msgBodyArr["clue"][0]["s_mobile_phone"],//手机
            "formerOwner"       => $msgBodyArr["clue"][0]["s_former_owner"],//前所属人
            "clueName"          => $msgBodyArr["clue"][0]["s_clue_name"],//姓名
            "owner"             => $msgBodyArr["clue"][0]["s_owner"],//所属人
            "clueStatus"        => $msgBodyArr["clue"][0]["s_clue_status"],//状态
            "provinceCode"      => $msgBodyArr["clue"][0]["s_location"][0] ?? "",//省份
            "cityCode"          => $msgBodyArr["clue"][0]["s_location"][1] ?? "",//市
            "districtCode"      => $msgBodyArr["clue"][0]["s_location"][2] ?? "",//区
            "provinceText"      => $msgBodyArr["clue"][0]["s_location_str"][0] ?? "",//省份
            "cityText"          => $msgBodyArr["clue"][0]["s_location_str"][1] ?? "",//市
            "districtText"      => $msgBodyArr["clue"][0]["s_location_str"][2] ?? "",//区
            "lon"               => $locationArr["lon"] ?? "",//经度
            "lat"               => $locationArr["lat"] ?? "",//维度
            "createdXkUserWid"  => $msgBodyArr["clue"][0]["s_create_user_wid"],// 创建人
            "updatedXkUserWid"  => $msgBodyArr["clue"][0]["s_last_update_user_wid"],//上次更新用户
            "createdXkAt"       => strtotime($msgBodyArr["clue"][0]["s_create_time"]),//创建时间
            "updatedXkAt"       => strtotime($msgBodyArr["clue"][0]["s_last_update_time"]),//上次更新时间
            "getTime"           => $msgBodyArr["clue"][0]["c_huodeshijian"] ?? "",
            "formatCreatedXkAt" => formatDate(
                strtotime($msgBodyArr["clue"][0]["s_create_time"]),
                formatDate(time())
            ),
            "formatUpdatedXkAt" => formatDate(
                strtotime($msgBodyArr["clue"][0]["s_last_update_time"]),
                formatDate(time())
            ),
            "formatCreatedAt"   => formatDate(time()),
            "formatUpdatedAt"   => formatDate(time()),
            "createdAt"         => time(),
            "updatedAt"         => time(),
        ]);

        ClueChangeOwnerRecordModel::query()->insert([
            "clueId"          => $msgBodyArr["clue"][0]["id"],
            "newOwnerId"      => $msgBodyArr["clue"][0]["s_owner"],//所属人
            "isMerchants"     => self::checkIsMerchants($msgBodyArr["clue"][0]["s_owner"]),//所属人
            "buildTime"       => $msgBodyArr["buildTime"],
            "operateWid"      => $msgBodyArr["clue"][0]["s_create_user_wid"],
            "formatCreatedAt" => formatDate(time()),
            "formatUpdatedAt" => formatDate(time()),
            "createdAt"       => time(),
            "updatedAt"       => time(),
        ]);
    }

    /**
     * 线索转客户
     *
     * @param object $params
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function clueToCustomerNotify(object $params)
    {
        $msgBodyArr  = json_decode($params->msg_body, true);
        $locationArr = jsonToArr($msgBodyArr["customer"]["s_location"][4] ?? "", []);

        $nowStagePercent = collect(CustomerRemote::stageList())
            ->where("id", $msgBodyArr["customer"]["s_customer_stage"])->first();

        ClueToCustomerModel::query()->insert([
            "businessId"        => $params->business_id,
            "event"             => $params->event,
            "publicAccountId"   => $params->public_account_id,
            "notifyId"          => $params->id,
            "topic"             => $params->topic,
            "originalMsgBody"   => $params->msg_body,
            "buildTime"         => $msgBodyArr["buildTime"],
            "formatBuildTime"   => formatDate(substr($msgBodyArr["buildTime"], 0, 10), formatDate(time())),
            "clueId"            => $msgBodyArr["key"] ?? "",
            // 线索id
            "customerId"        => $msgBodyArr["customer"]["id"] ?? "",
            // 客户id
            "createdXkUserWid"  => $msgBodyArr["customer"]["s_create_user_wid"],
            // 创建人
            "updatedXkUserWid"  => $msgBodyArr["customer"]["s_last_update_user_wid"] ?? 0,
            //上次更新用户
            "createdXkAt"       => strtotime($msgBodyArr["customer"]["s_create_time"]),
            //创建时间
            "updatedXkAt"       => strtotime($msgBodyArr["customer"]["s_last_update_time"]),
            //上次更新时间
            "formatCreatedXkAt" => formatDate(
                strtotime($msgBodyArr["customer"]["s_create_time"]), formatDate(time())
            ),
            //创建时间
            "formatUpdatedXkAt" => formatDate(
                strtotime($msgBodyArr["customer"]["s_last_update_time"]),
                formatDate(time())
            ),
            //上次更新时间
            "createdAt"         => time(),
            "updatedAt"         => time(),
            "formatCreatedAt"   => formatDate(time()),
            "formatUpdatedAt"   => formatDate(time()),
        ]);

        CustomerStageDataModel::query()->insert([
            "businessId"      => $params->business_id,
            "event"           => $params->event,
            "publicAccountId" => $params->public_account_id,
            "notifyId"        => $params->id,
            "topic"           => $params->topic,
            "originalMsgBody" => $params->msg_body,
            "buildTime"       => $msgBodyArr["buildTime"],
            "formatBuildTime" => formatDate(substr($msgBodyArr["buildTime"], 0, 10), formatDate(time())),
            "customerId"      => $msgBodyArr["customer"]["id"] ?? "", // 客户id
            "interactiveMode" => $msgBodyArr["customer"]["c_jiaohufangshi1"] ?? "", // 交互方式
            "source"          => $msgBodyArr["customer"]["c_xinxilaiyuan"] ?? "", // 线索来源
            "followStatus"    => $msgBodyArr["customer"]["s_follow_status"],//跟进状态
            "mobilePhone"     => $msgBodyArr["customer"]["s_mobile_phone"],//手机
            "formerOwner"     => $msgBodyArr["customer"]["s_former_owner"],//前所属人
            "customerName"    => $msgBodyArr["customer"]["s_customer_name"],//姓名
            "owner"           => $msgBodyArr["customer"]["s_owner"],//所属人
            "customerStatus"  => $msgBodyArr["customer"]["s_customer_status"],//状态
            "customerStage"   => $msgBodyArr["customer"]["s_customer_stage"],//阶段
            "originalStage"   => json_encode($nowStagePercent, JSON_UNESCAPED_UNICODE),//阶段
            "stageName"       => $nowStagePercent["stageName"],//阶段
            "stagePercent"    => $nowStagePercent["stagePercent"],//阶段
            "stageProcess"    => $nowStagePercent["stageProcess"],//阶段
            "remark"          => $msgBodyArr["customer"]["s_remark"] ?? "",
            "advertiserUid"   => $msgBodyArr["customer"]["c_guanggaozhuid"] ?? 0,
            "advertiserName"  => $msgBodyArr["customer"]["c_guanggaozhumingcheng"] ?? "",
            "provinceCode"    => $msgBodyArr["customer"]["s_location"][0] ?? "",//省份
            "cityCode"        => $msgBodyArr["customer"]["s_location"][1] ?? "",//市
            "districtCode"    => $msgBodyArr["customer"]["s_location"][2] ?? "",//区
            "provinceText"    => $msgBodyArr["customer"]["s_location_str"][0] ?? "",//省份
            "cityText"        => $msgBodyArr["customer"]["s_location_str"][1] ?? "",//市
            "districtText"    => $msgBodyArr["customer"]["s_location_str"][2] ?? "",//区
            "lon"             => $locationArr["lon"] ?? "",//经度
            "lat"             => $locationArr["lat"] ?? "",//维度

            "createdXkUserWid"  => $msgBodyArr["customer"]["s_create_user_wid"],// 创建人
            "updatedXkUserWid"  => $msgBodyArr["customer"]["s_last_update_user_wid"] ?? 0,//上次更新用户
            "createdXkAt"       => strtotime($msgBodyArr["customer"]["s_create_time"]),//创建时间
            "updatedXkAt"       => strtotime($msgBodyArr["customer"]["s_last_update_time"]),//上次更新时间
            "getTime"           => $msgBodyArr["customer"]["c_huodeshijian"] ?? "", // 获得时间
            "createdAt"         => time(),
            "updatedAt"         => time(),
            "formatCreatedAt"   => formatDate(time()),
            "formatUpdatedAt"   => formatDate(time()),
            //上次更新时间
            "formatCreatedXkAt" => formatDate(
                strtotime($msgBodyArr["customer"]["s_create_time"]), formatDate(time())
            ),
            //创建时间
            "formatUpdatedXkAt" => formatDate(
                strtotime($msgBodyArr["customer"]["s_last_update_time"]),
                formatDate(time())
            ),
        ]);
    }

    /**
     * 更新客户信息
     *
     * @param object $params
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function customerUpdateNotify(object $params)
    {
        $msgBodyArr            = json_decode($params->msg_body, true);
        $customerId            = $msgBodyArr["id"];
        $customerStage         = $msgBodyArr["fieldKeyValue"]["s_customer_stage"][0];
        $lastCustomerStageData = CustomerStageDataModel::query()
                                                       ->where("customerId", $customerId)
                                                       ->orderBy("id", "desc")
                                                       ->first();

        if (!$lastCustomerStageData || $lastCustomerStageData->customerStage != $customerStage) {
            // 阶段存量数据不存在 || 阶段发生变更
            $customerDetail = CustomerRemote::detail($customerId)["customerInfoList"];
            list($locationVal, $locationValStr) = self::getCustomerField($customerDetail, "s_location", []);
            $locationArr     = jsonToArr($locationVal[4] ?? "", []);
            $nowStagePercent = collect(CustomerRemote::stageList())->where("id", $customerStage)->first();

            $insertData = [
                "businessId"      => $params->business_id,
                "event"           => $params->event,
                "publicAccountId" => $params->public_account_id,
                "notifyId"        => $params->id,
                "topic"           => $params->topic,
                "originalMsgBody" => $params->msg_body,
                "customerId"      => $customerId,
                "interactiveMode" => self::getCustomerField($customerDetail, "c_jiaohufangshi1", ""),
                // 交互方式
                "source"          => self::getCustomerField($customerDetail, "c_xinxilaiyuan", ""),
                // 线索来源
                "followStatus"    => self::getCustomerField($customerDetail, "s_follow_status", ""),
                //跟进状态
                "mobilePhone"     => self::getCustomerField($customerDetail, "s_mobile_phone", ""),
                //手机
                "formerOwner"     => self::getCustomerField($customerDetail, "s_former_owner", ""),
                //前所属人
                "customerName"    => self::getCustomerField($customerDetail, "s_customer_name", ""),
                //姓名
                "owner"           => self::getCustomerField($customerDetail, "s_owner", ""),
                //所属人
                "customerStatus"  => self::getCustomerField($customerDetail, "s_customer_status", ""),
                //状态
                "customerStage"   => self::getCustomerField($customerDetail, "s_customer_stage", ""),
                //阶段
                "originalStage"   => json_encode($nowStagePercent, JSON_UNESCAPED_UNICODE),
                //阶段
                "stageName"       => $nowStagePercent["stageName"],
                //阶段
                "stagePercent"    => $nowStagePercent["stagePercent"],
                //阶段
                "stageProcess"    => $nowStagePercent["stageProcess"],
                //阶段
                "remark"          => self::getCustomerField($customerDetail, "s_remark", ""),
                "advertiserUid"   => self::getCustomerField($customerDetail, "c_guanggaozhuid", 0),
                "advertiserName"  => self::getCustomerField($customerDetail, "c_guanggaozhumingcheng", ""),
                "provinceCode"    => $locationVal[0] ?? "",
                //省份
                "cityCode"        => $locationVal[1] ?? "",
                //市
                "districtCode"    => $locationVal[2] ?? "",
                //区
                "provinceText"    => $locationValStr[0] ?? "",
                //省份
                "cityText"        => $locationValStr[1] ?? "",
                //市
                "districtText"    => $locationValStr[2] ?? "",
                //区
                "lon"             => $locationArr["lon"] ?? "",
                //经度
                "lat"             => $locationArr["lat"] ?? "",
                //维度

                "createdXkUserWid"  => (int)self::getCustomerField($customerDetail, "o_corp_user", 0),
                // 创建人
                "updatedXkUserWid"  => (int)self::getCustomerField($customerDetail, "o_corp_user", 0),
                //上次更新用户
                "createdXkAt"       => strtotime(self::getCustomerField($customerDetail, "s_create_time", 0)),
                //创建时间
                "updatedXkAt"       => strtotime(self::getCustomerField($customerDetail, "s_last_update_time", 0)),
                //上次更新时间
                "getTime"           => self::getCustomerField($customerDetail, "c_huodeshijian", ""),
                // 获得时间
                "formatCreatedXkAt" => formatDate(
                    strtotime(self::getCustomerField($customerDetail, "s_create_time", 0)),
                    formatDate(time())
                ),
                "formatUpdatedXkAt" => formatDate(
                    strtotime(self::getCustomerField($customerDetail, "s_last_update_time", 0)),
                    formatDate(time())
                ),
                "createdAt"         => time(),
                "updatedAt"         => time(),
                "formatCreatedAt"   => formatDate(time()),
                "formatUpdatedAt"   => formatDate(time()),
            ];

            CustomerStageDataModel::query()->insert($insertData);
        }
    }

    /**
     * 变更线索所属人
     *
     * @param object $params
     */
    public static function clueChangeOwnerNotify(object $params)
    {
        $msgBodyArr  = $params->msg_body;
        $isMerchants = self::checkIsMerchants($msgBodyArr["newOwnerId"]);
        $insertData  = collect($msgBodyArr["keys"])->map(function ($clueId) use ($msgBodyArr, $isMerchants) {
            return [
                "clueId"          => $clueId,
                "newOwnerId"      => $msgBodyArr["newOwnerId"],//所属人
                "isMerchants"     => $isMerchants,//是否是招商人员
                "buildTime"       => $msgBodyArr["buildTime"],
                "operateWid"      => $msgBodyArr["wid"],
                "createdAt"       => time(),
                "updatedAt"       => time(),
                "formatCreatedAt" => formatDate(time()),
                "formatUpdatedAt" => formatDate(time()),
            ];
        })->values();

        ClueChangeOwnerRecordModel::query()->insert($insertData->toArray());
    }

    /**
     * 判断是否为招商人员
     *
     * @param int $wid
     * @return int
     */
    public static function checkIsMerchants(int $wid): int
    {
        return (int)UserModel::query()->where("wid", $wid)->where("isMerchants", UserModel::IS_MERCHANTS_YES)->first();
    }

    /**
     * 获取自定义字段信息
     *
     * @param array $customerList
     * @param string $customerField
     * @param $default
     * @return mixed
     */
    public static function getCustomerField(array $customerList, string $customerField, $default)
    {
        $fieldGroup = collect($customerList)->where("apiName", "$customerField")->first();
        switch ($customerField) {
            case "s_location":
                return [
                    attributeGet($fieldGroup, "value", $default),
                    attributeGet($fieldGroup, "valueStr", $default)
                ];
            default:
                return attributeGet($fieldGroup, "value.0", $default);
        }
    }
}
